<template>
  <view class="skill-list-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">技能认证</block>
    </cu-custom>

    <!-- 技能概览 -->
    <view class="skill-overview margin-top bg-white">
      <view class="overview-header padding">
        <text class="text-lg text-bold">我的技能</text>
      </view>
      <view class="skill-stats padding">
        <view class="stats-row">
          <view class="stat-item">
            <view class="stat-number text-green">{{ skillStats.certified }}</view>
            <view class="stat-label">已认证</view>
          </view>
          <view class="stat-item">
            <view class="stat-number text-orange">{{ skillStats.pending }}</view>
            <view class="stat-label">审核中</view>
          </view>
          <view class="stat-item">
            <view class="stat-number text-blue">{{ skillStats.available }}</view>
            <view class="stat-label">可申请</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 已认证技能 -->
    <view class="certified-skills margin-top bg-white" v-if="certifiedSkills.length > 0">
      <view class="section-title padding">
        <text class="text-lg text-bold">已认证技能</text>
      </view>
      <view class="skill-grid padding">
        <view v-for="skill in certifiedSkills" :key="skill.id" 
              class="skill-card certified">
          <view class="skill-icon">
            <text class="cuIcon-medal text-yellow"></text>
          </view>
          <view class="skill-info">
            <view class="skill-name">{{ skill.workTypeName }}</view>
            <view class="skill-level" :class="skill.levelClass">{{ skill.levelText }}</view>
            <view class="skill-date text-sm text-gray">{{ formatDate(skill.certifiedDate) }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 审核中技能 -->
    <view class="pending-skills margin-top bg-white" v-if="pendingSkills.length > 0">
      <view class="section-title padding">
        <text class="text-lg text-bold">审核中技能</text>
      </view>
      <view class="pending-list padding">
        <view v-for="skill in pendingSkills" :key="skill.id" 
              class="pending-item">
          <view class="flex align-center justify-between">
            <view class="flex align-center">
              <view class="pending-icon bg-orange">
                <text class="cuIcon-time text-white"></text>
              </view>
              <view class="margin-left">
                <view class="skill-name">{{ skill.workTypeName }}</view>
                <view class="text-sm text-gray">申请时间：{{ formatDate(skill.applyDate) }}</view>
              </view>
            </view>
            <view class="pending-status">审核中</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 可申请技能 -->
    <view class="available-skills margin-top bg-white">
      <view class="section-title padding">
        <text class="text-lg text-bold">可申请技能</text>
      </view>
      <view class="available-list padding">
        <view v-for="skill in availableSkills" :key="skill.id" 
              class="available-item" 
              @click="applySkill(skill)">
          <view class="flex align-center justify-between">
            <view class="flex align-center">
              <view class="available-icon bg-blue">
                <text class="cuIcon-add text-white"></text>
              </view>
              <view class="margin-left">
                <view class="skill-name">{{ skill.workTypeName }}</view>
                <view class="skill-desc text-sm text-gray">{{ skill.description }}</view>
              </view>
            </view>
            <view class="apply-btn">
              <text class="cuIcon-right text-gray"></text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 技能认证申请弹窗 -->
    <view v-if="showApplyModal" class="apply-modal" @click="showApplyModal = false">
      <view class="apply-content" @click.stop>
        <view class="apply-header padding">
          <text class="text-lg text-bold">申请技能认证</text>
          <text class="cuIcon-close float-right" @click="showApplyModal = false"></text>
        </view>
        <view class="apply-form padding">
          <view class="form-item">
            <text class="form-label">技能名称</text>
            <text class="form-value">{{ selectedSkill.workTypeName }}</text>
          </view>
          <view class="form-item">
            <text class="form-label">申请等级</text>
            <picker :value="selectedLevel" :range="levelOptions" @change="onLevelChange">
              <view class="picker-value">{{ levelOptions[selectedLevel] }}</view>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">工作经验</text>
            <textarea v-model="applyForm.experience" 
                     placeholder="请描述相关工作经验" 
                     class="form-textarea"></textarea>
          </view>
          <view class="form-item">
            <text class="form-label">证明材料</text>
            <view class="upload-area" @click="uploadFiles">
              <text class="cuIcon-add text-gray"></text>
              <text class="text-gray margin-left-sm">上传证明文件</text>
            </view>
          </view>
        </view>
        <view class="apply-actions padding">
          <button class="cu-btn bg-gray margin-right" @click="showApplyModal = false">取消</button>
          <button class="cu-btn bg-blue" @click="submitApplication">提交申请</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import mesApi from '../../../api/mes'

export default {
  data() {
    return {
      skillStats: {
        certified: 0,
        pending: 0,
        available: 0
      },
      certifiedSkills: [],
      pendingSkills: [],
      availableSkills: [],
      showApplyModal: false,
      selectedSkill: {},
      selectedLevel: 0,
      levelOptions: ['基础', '熟练', '专家'],
      applyForm: {
        experience: '',
        files: []
      }
    }
  },

  onLoad() {
    this.loadSkillData()
  },

  methods: {
    async loadSkillData() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        // 获取员工技能数据
        const response = await mesApi.skill.getEmployeeSkills(this.getCurrentEmployeeId())
        
        // 处理已认证技能
        this.certifiedSkills = response.data.certified.map(skill => ({
          ...skill,
          levelClass: this.calculateLevelClass(skill.level),
          levelText: this.calculateLevelText(skill.level)
        }))
        
        // 处理审核中技能
        this.pendingSkills = response.data.pending || []
        
        // 处理可申请技能
        this.availableSkills = response.data.available || []
        
        // 计算统计数据
        this.skillStats = {
          certified: this.certifiedSkills.length,
          pending: this.pendingSkills.length,
          available: this.availableSkills.length
        }
        
      } catch (error) {
        console.error('加载技能数据失败:', error)
        // 模拟数据
        this.loadMockData()
      } finally {
        uni.hideLoading()
      }
    },

    loadMockData() {
      this.certifiedSkills = [
        {
          id: 1,
          workTypeName: '切割',
          level: 3,
          levelClass: 'level-expert',
          levelText: '专家',
          certifiedDate: '2024-01-15'
        },
        {
          id: 2,
          workTypeName: '组装',
          level: 2,
          levelClass: 'level-skilled',
          levelText: '熟练',
          certifiedDate: '2024-02-20'
        }
      ]
      
      this.pendingSkills = [
        {
          id: 3,
          workTypeName: '打包',
          applyDate: '2024-03-01'
        }
      ]
      
      this.availableSkills = [
        {
          id: 4,
          workTypeName: '质检',
          description: '产品质量检查和验收'
        },
        {
          id: 5,
          workTypeName: '设备维护',
          description: '生产设备日常维护保养'
        }
      ]
      
      this.skillStats = {
        certified: 2,
        pending: 1,
        available: 2
      }
    },

    calculateLevelClass(level) {
      const levelMap = {
        1: 'level-basic',
        2: 'level-skilled', 
        3: 'level-expert'
      }
      return levelMap[level] || 'level-basic'
    },

    calculateLevelText(level) {
      const levelMap = {
        1: '基础',
        2: '熟练',
        3: '专家'
      }
      return levelMap[level] || '基础'
    },

    applySkill(skill) {
      this.selectedSkill = skill
      this.selectedLevel = 0
      this.applyForm = {
        experience: '',
        files: []
      }
      this.showApplyModal = true
    },

    onLevelChange(e) {
      this.selectedLevel = e.detail.value
    },

    uploadFiles() {
      uni.chooseFile({
        count: 3,
        type: 'file',
        success: (res) => {
          this.applyForm.files = res.tempFiles
          uni.showToast({
            title: '文件选择成功',
            icon: 'success'
          })
        }
      })
    },

    async submitApplication() {
      if (!this.applyForm.experience.trim()) {
        uni.showToast({
          title: '请填写工作经验',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({ title: '提交中...' })
        
        const applicationData = {
          workTypeId: this.selectedSkill.id,
          level: this.selectedLevel + 1,
          experience: this.applyForm.experience,
          files: this.applyForm.files
        }
        
        await mesApi.skill.applySkillCertification(applicationData)
        
        uni.showToast({
          title: '申请提交成功',
          icon: 'success'
        })
        
        this.showApplyModal = false
        this.loadSkillData()
        
      } catch (error) {
        console.error('提交申请失败:', error)
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    getCurrentEmployeeId() {
      // 从用户信息中获取员工ID
      const userInfo = uni.getStorageSync('userInfo')
      return (userInfo && userInfo.id) || 1
    },

    formatDate(dateStr) {
      if (!dateStr) return '--'
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.skill-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.skill-overview {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .overview-header {
    border-bottom: 1rpx solid #f0f0f0;
  }
  
  .stats-row {
    display: flex;
    justify-content: space-around;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.certified-skills, .pending-skills, .available-skills {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
}

.section-title {
  border-bottom: 1rpx solid #f0f0f0;
}

.skill-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx;
  
  .skill-card {
    padding: 24rpx;
    border-radius: 8rpx;
    background-color: #fafafa;
    text-align: center;
    
    &.certified {
      background-color: #f6ffed;
      border: 1rpx solid #b7eb8f;
    }
    
    .skill-icon {
      font-size: 48rpx;
      margin-bottom: 12rpx;
    }
    
    .skill-name {
      font-size: 28rpx;
      font-weight: bold;
      margin-bottom: 8rpx;
    }
    
    .skill-level {
      font-size: 24rpx;
      padding: 4rpx 12rpx;
      border-radius: 12rpx;
      color: white;
      
      &.level-basic {
        background-color: #52c41a;
      }
      
      &.level-skilled {
        background-color: #1890ff;
      }
      
      &.level-expert {
        background-color: #f5222d;
      }
    }
    
    .skill-date {
      margin-top: 8rpx;
    }
  }
}

.pending-list, .available-list {
  .pending-item, .available-item {
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .pending-icon, .available-icon {
      width: 48rpx;
      height: 48rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .cuIcon {
        font-size: 24rpx;
      }
    }
    
    .skill-name {
      font-size: 28rpx;
      font-weight: bold;
      margin-bottom: 4rpx;
    }
    
    .pending-status {
      color: #fa8c16;
      font-size: 24rpx;
    }
  }
}

.apply-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .apply-content {
    background-color: white;
    border-radius: 12rpx;
    margin: 0 48rpx;
    width: calc(100% - 96rpx);
    max-height: 80vh;
    overflow: hidden;
    
    .apply-header {
      border-bottom: 1rpx solid #f0f0f0;
      position: relative;
      
      .cuIcon-close {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        font-size: 32rpx;
        color: #999;
      }
    }
    
    .apply-form {
      max-height: 60vh;
      overflow-y: auto;
      
      .form-item {
        margin-bottom: 32rpx;
        
        .form-label {
          display: block;
          font-size: 28rpx;
          color: #333;
          margin-bottom: 12rpx;
        }
        
        .form-value {
          font-size: 28rpx;
          color: #666;
        }
        
        .picker-value {
          padding: 16rpx;
          border: 1rpx solid #d9d9d9;
          border-radius: 8rpx;
          font-size: 28rpx;
        }
        
        .form-textarea {
          width: 100%;
          min-height: 120rpx;
          padding: 16rpx;
          border: 1rpx solid #d9d9d9;
          border-radius: 8rpx;
          font-size: 28rpx;
        }
        
        .upload-area {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 120rpx;
          border: 2rpx dashed #d9d9d9;
          border-radius: 8rpx;
        }
      }
    }
    
    .apply-actions {
      border-top: 1rpx solid #f0f0f0;
      display: flex;
      gap: 16rpx;
      
      .cu-btn {
        flex: 1;
      }
    }
  }
}
</style>
